package com.xcity.logupload.util;

import java.lang.reflect.Field;

public class ReflectUtils {
	
	public static void setField(Object object, String fieldName, Object fieldValue) {
		setField(object.getClass(), object, fieldName, fieldValue);
	}

	public static void setField(Class<?> objectClass, Object object, String fieldName, Object fieldValue) {
		try {
			Field f = objectClass.getDeclaredField(fieldName);
			f.setAccessible(true);
			f.set(object, cast(fieldValue, f.getType()));
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	private static Object cast(Object src, Class<?> targetType) {
		if (src != null && targetType.isAssignableFrom(src.getClass())) {
			return src;
		}
		if (targetType == String.class) {
			return src != null ? src.toString() : null;
		}
		if (targetType == byte.class || targetType == Byte.class) {
			return NumberUtils.parseByte(src);
		}
		if (targetType == boolean.class || targetType == Boolean.class) {
			return NumberUtils.parseBoolean(src);
		}
		if (targetType == short.class || targetType == Short.class) {
			return NumberUtils.parseShort(src);
		}
		if (targetType == int.class || targetType == Integer.class) {
			return NumberUtils.parseInt(src);
		}
		if (targetType == long.class || targetType == Long.class) {
			return NumberUtils.parseLong(src);
		}
		if (targetType == float.class || targetType == Float.class) {
			return NumberUtils.parseFloat(src);
		}
		if (targetType == double.class || targetType == Double.class) {
			return NumberUtils.parseDouble(src);
		}
		if (targetType == char.class || targetType == Character.class) {
			return NumberUtils.parseChar(src);
		}
		if (src != null && targetType.isEnum()) {
			int ordinal = NumberUtils.parseInt(src, -1);
			if (ordinal != -1) {
				Object[] vals = targetType.getEnumConstants();
				if (ordinal >= 0 && ordinal < vals.length) {
					return vals[ordinal];
				}
			}
			return Enum.valueOf((Class<? extends Enum>) targetType, src.toString());
		}
		return src;
	}
	
}
